<?php
/**
 * 会员模型
 *
 *
 *
 *
 * @copyright  Copyright (c) 中国追溯
 * @since      File available since Release v1.1
 */
defined('InShopNC') or exit('Access Invalid!');
class hunterModel extends Model {

    public function __construct(){
        parent::__construct('hunter');
    }

    /**
     * 会员详细信息（查库）
     * @param array $condition
     * @param string $field
     * @return array
     */
    public function getInfo($condition, $field = '*', $master = false) {
        return $this->table('hunter')->field($field)->where($condition)->master($master)->find();
    }

    /**
     * 取得会员详细信息（优先查询缓存）
     * 如果未找到，则缓存所有字段
     * @param int $hunter_id
     * @param string $field 需要取得的缓存键值, 例如：'*','hunter_name,hunter_sex'
     * @return array
     */
    public function getInfoByID($id, $fields = '*') {
        $info = $this->getInfo(array('hunter_id'=>$id),$fields,true);
        return $info;
    }




    /**
     * 会员列表
     * @param array $condition
     * @param string $field
     * @param number $page
     * @param string $order
     */
    public function getList($condition = array(), $field = '*', $page = null, $order = 'hunter_id desc', $limit = '') {
        return $this->table('hunter')->field($field)->where($condition)->page($page)->order($order)->limit($limit)->select();
    }

    /**
     * 会员数量
     * @param array $condition
     * @return int
     */
    public function getCount($condition) {
        return $this->table('hunter')->where($condition)->count();
    }

    /**
     * 编辑会员
     * @param array $condition
     * @param array $data
     */
    public function edit($condition, $data) {
        $update = $this->table('hunter')->where($condition)->update($data);
        if ($update && $condition['hunter_id']) {
            dcache($condition['hunter_id'], 'hunter');
        }
        return $update;
    }

    /**
     * 登录时创建会话SESSION
     *
     * @param array $hunter_info 会员信息
     */
    public function createSession($hunter_info = array(),$reg = false) {
        if (empty($hunter_info) || !is_array($hunter_info)) return ;

        $_SESSION['is_login']   = '1';
        $_SESSION['hunter_id']  = $hunter_info['hunter_id'];
        $_SESSION['hunter_name']= $hunter_info['hunter_name'];
        $_SESSION['hunter_email']= $hunter_info['hunter_email'];
        $_SESSION['is_buy']     = isset($hunter_info['is_buy']) ? $hunter_info['is_buy'] : 1;
        $_SESSION['avatar']     = $hunter_info['hunter_avatar'];
        $_SESSION['is_distributer'] = ($hunter_info['distri_state'] == 2) ? 1 : 0;

        // 头衔COOKIE
        $this->set_avatar_cookie();

        $seller_info = Model('seller')->getSellerInfo(array('hunter_id'=>$_SESSION['hunter_id']));
        $_SESSION['store_id'] = $seller_info['store_id'];

        if (trim($hunter_info['hunter_qqopenid'])){
            $_SESSION['openid']     = $hunter_info['hunter_qqopenid'];
        }
        if (trim($hunter_info['hunter_sinaopenid'])){
            $_SESSION['slast_key']['uid'] = $hunter_info['hunter_sinaopenid'];
        }

        if (!$reg) {
            //添加会员积分
            $this->addPoint($hunter_info);
            //添加会员经验值
            $this->addExppoint($hunter_info);
            $update_info    = array(
                'hunter_login_num'=> ($hunter_info['hunter_login_num']+1),
                'hunter_login_time'=> TIMESTAMP,
                'hunter_old_login_time'=> $hunter_info['hunter_login_time'],
                'hunter_login_ip'=> getIp(),
                'hunter_old_login_ip'=> $hunter_info['hunter_login_ip']
            );
            $this->edit(array('hunter_id'=>$hunter_info['hunter_id']),$update_info);
        }

        setNcCookie('cart_goods_num','',-3600);
        // cookie中的cart存入数据库
        Model('cart')->mergecart($hunter_info,$_SESSION['store_id']);

        // 自动登录
        if ($hunter_info['auto_login'] == 1) {
            $this->auto_login();
        }
    }

    /**
     * 7天内自动登录
     */
    public function auto_login() {
        // 自动登录标记 保存7天
        setNcCookie('auto_login', encrypt($_SESSION['hunter_id'], MD5_KEY), 7*24*60*60);
    }

    public function set_avatar_cookie() {
        setNcCookie('hunter_avatar', $_SESSION['avatar'], 365*24*60*60);
    }

    /**
     *
     */
    public function login($login_info) {
        if (process::islock('login')) {
            return array('error' => '您的操作过于频繁，请稍后再试');
        }
        process::addprocess('login');
        $user_name = $login_info['user_name'];
        $password = $login_info['password'];
        $obj_validate = new Validate();
        $obj_validate->validateparam = array(
            array(
                "input" => $user_name,
                "require" => "true",
                "message" => "请填写用户名"
            ),
            array(
                "input" => $user_name,
                "validator" => "username",
                "message" => "请填写字母、数字、中文、_"
            ),
            array(
                "input" => $user_name,
                "max" => "20",
                "min" => "3",
                "validator" => "length",
                "message" => "用户名长度要在6~20个字符"
            ),
            array(
                "input" => $password,
                "require" => "true",
                "message" => "密码不能为空"
            )
        );
        $error = $obj_validate->validate();
        if ($error != ''){
            return array('error' => $error);
        }
        $condition = array();
        $condition['hunter_name'] = $user_name;
        $condition['hunter_passwd'] = md5($password);
        $hunter_info = $this->getInfo($condition);
        if(empty($hunter_info) && preg_match('/^0?(13|15|17|18|14|19|16)[0-9]{9}$/i', $user_name)) {//根据会员名没找到时查手机号
            $condition = array();
            $condition['hunter_mobile'] = $user_name;
            $condition['hunter_passwd'] = md5($password);
            $hunter_info = $this->getInfo($condition);
        }
        if(empty($hunter_info) && (strpos($user_name, '@') > 0)) {//按邮箱和密码查询会员
            $condition = array();
            $condition['hunter_email'] = $user_name;
            $condition['hunter_passwd'] = md5($password);
            $hunter_info = $this->getInfo($condition);
        }
        if (!empty($hunter_info)) {
            if(!$hunter_info['hunter_state']){
                return array('error' => '账号被停用');
            }
            process::clear('login');

            //添加会员积分
            $this->addPoint($hunter_info);
            //添加会员经验值
            $this->addExppoint($hunter_info);

            $update_info    = array(
                'hunter_login_num'=> ($hunter_info['hunter_login_num']+1),
                'hunter_login_time'=> TIMESTAMP,
                'hunter_old_login_time'=> $hunter_info['hunter_login_time'],
                'hunter_login_ip'=> getIp(),
                'hunter_old_login_ip'=> $hunter_info['hunter_login_ip']
            );
            $this->edit(array('hunter_id'=>$hunter_info['hunter_id']),$update_info);

            return $hunter_info;
        } else {
            return array('error' => '登录失败');
        }
    }

    /**
     * 注册
     */
    public function register($register_info) {
        //重复注册验证
        if (process::islock('reg')){
            return array('error' => '您的操作过于频繁，请稍后再试');
        }
        // 注册验证
        $obj_validate = new Validate();
        $obj_validate->validateparam = array(
            array(
                "input" => $register_info["username"],
                "require" => "true",
                "message" => "请填写用户名"
            ),
            array(
                "input" => $register_info["username"],
                "validator" => "username",
                "message" => "请填写字母、数字、中文、_"
            ),
            array(
                "input" => $register_info["username"],
                "max" => "20",
                "min" => "6",
                "validator" => "length",
                "message" => "用户名长度要在6~20个字符"
            ),
            array(
                "input" => $register_info["password"],
                "require" => "true",
                "message" => "密码不能为空"
            ),
            array(
                "input" => $register_info["password_confirm"],
                "require" => "true",
                "validator" => "Compare",
                "operator" => "==",
                "to" => $register_info["password"],
                "message" => "密码与确认密码不相同"
            ),
            array(
                "input" => $register_info["email"],
                "require" => "true",
                "validator" => "email",
                "message" => "电子邮件格式不正确"
            ),
        );
        $error = $obj_validate->validate();
        if ($error != ''){
            return array('error' => $error);
        }

        if(is_numeric($register_info["username"])) {
            return array('error' => '用户名不能为纯数字');
        }
        //检测是否含有敏感词
        $model_setting = Model('setting');
        $sensitive_info = $model_setting->getRowSetting('sensitive_set');
        if ($sensitive_info !== false) {
            $sensitive_list = @unserialize($sensitive_info['value']);
        }
        if (!is_array($sensitive_list)) {
            $sensitive_list = array();
        }
        foreach ($sensitive_list as $v) {
            if($v['name'] == 'hunter_name'){
                $is_open = $v['is_open'];
                break;
            }
        }
        if($is_open == 1 && sensitiveWordDetection($register_info["username"])){
            return array('error' => '用户名含有敏感词');
        }

        // 验证用户名是否重复
        $check_hunter_name  = $this->getInfo(array('member_name'=>$register_info['username']));
        if(is_array($check_member_name) && count($check_member_name) > 0) {
            return array('error' => '用户名已存在');
        }

        // 验证邮箱是否重复
        $check_member_email = $this->getMemberInfo(array('member_email'=>$register_info['email']));
        if(is_array($check_member_email) && count($check_member_email)>0) {
            return array('error' => '邮箱已存在');
        }
        // 会员添加
        $member_info    = array();
        $member_info['member_name']     = $register_info['username'];
        $member_info['member_passwd']   = $register_info['password'];
        $member_info['member_email']        = $register_info['email'];
        $insert_id  = $this->addMember($member_info);
        if($insert_id) {
            $member_info['member_id'] = $insert_id;
            $member_info['is_buy'] = 1;
            process::addprocess('reg');
            return $member_info;
        } else {
            return array('error' => '注册失败');
        }
    }

    /**
     * 注册商城会员
     *
     * @param   array $param 会员信息
     * @return  array 数组格式的返回结果
     */
    public function add($param) {
        if(empty($param)) {
            return false;
        }
        try {
            $this->beginTransaction();
            $hunter_info    = array();
            $hunter_info['hunter_name']         = $param['hunter_name'];
            $hunter_info['hunter_passwd']       = md5(trim($param['hunter_passwd']));
            $hunter_info['hunter_email']               = $param['email'];
            $hunter_info['hunter_add_time']            = TIMESTAMP;
            $hunter_info['hunter_login_time']          = TIMESTAMP;
            $hunter_info['hunter_old_login_time']      = TIMESTAMP;
            $hunter_info['hunter_login_ip']            = getIp();
            $hunter_info['hunter_old_login_ip']        = $hunter_info['hunter_login_ip'];

            $hunter_info['hunter_truename']     = $param['hunter_truename'];
            $hunter_info['hunter_sex']          = $param['hunter_sex'];
            $hunter_info['hunter_avatar']       = $param['hunter_avatar'];
            if ($param['hunter_mobile_bind']) {
                $hunter_info['hunter_mobile'] = $param['hunter_mobile'];
                $hunter_info['hunter_mobile_bind'] = $param['hunter_mobile_bind'];
            }
            if ($param['weixin_unionid']) {
                $hunter_info['weixin_unionid'] = $param['weixin_unionid'];
                $hunter_info['weixin_info'] = $param['weixin_info'];
                // 是否存在小程序openid
                if (isset($param['applet_wx_openid']) && !empty($param['applet_wx_openid'])) $member_info['applet_wx_openid'] = $param['applet_wx_openid'];
            }

            $insert_id  = $this->table('hunter')->insert($hunter_info);

            if (!$insert_id) {
                throw new Exception();
            }
            $insert = $this->addCommon(array('hunter_id'=>$insert_id));
            if (!$insert) {
                throw new Exception();
            }

            // 添加默认相册
            /*$insert = array();
            $insert['ac_name']      = '买家秀';
            $insert['member_id']    = $insert_id;
            $insert['ac_des']       = '买家秀默认相册';
            $insert['ac_sort']      = 1;
            $insert['is_default']   = 1;
            $insert['upload_time']  = TIMESTAMP;
            $rs = $this->table('sns_albumclass')->insert($insert);*/
            //添加会员积分
            /*if (C('points_isuse')){
                Model('points')->savePointsLog('regist',array('pl_memberid'=>$insert_id,'pl_membername'=>$param['member_name']),false);
            }*/

            $this->commit();
            return $insert_id;
        } catch (Exception $e) {
            $this->rollback();
            return false;
        }
    }

    /**
     * 会员登录检查
     *
     */
    public function checkloginMember() {
        if($_SESSION['is_login'] == '1') {
            @header("Location: index.php");
            exit();
        }
    }

    /**
     * 检查会员是否允许举报商品
     *
     */
    public function isMemberAllowInform($member_id) {
        $condition = array();
        $condition['member_id'] = $member_id;
        $member_info = $this->getMemberInfo($condition,'inform_allow');
        if(intval($member_info['inform_allow']) === 1) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * 取单条信息
     * @param unknown $condition
     * @param string $fields
     */
    public function getMemberCommonInfo($condition = array(), $fields = '*') {
        return $this->table('member_common')->where($condition)->field($fields)->find();
    }

    /**
     * 插入扩展表信息
     * @param unknown $data
     * @return Ambigous <mixed, boolean, number, unknown, resource>
     */
    public function addCommon($data) {
        return $this->table('hunter_common')->insert($data);
    }

    /**
     * 编辑会员扩展表
     * @param unknown $data
     * @param unknown $condition
     * @return Ambigous <mixed, boolean, number, unknown, resource>
     */
    public function editMemberCommon($data,$condition) {
        return $this->table('member_common')->where($condition)->update($data);
    }

    /**
     * 添加会员积分
     * @param unknown $member_info
     */
    public function addPoint($member_info) {
        if (!C('points_isuse') || empty($member_info)) return;

        //一天内只有第一次登录赠送积分
        if(trim(@date('Y-m-d',$member_info['member_login_time'])) == trim(date('Y-m-d'))) return;

        //加入队列
        $queue_content = array();
        $queue_content['member_id'] = $member_info['member_id'];
        $queue_content['member_name'] = $member_info['member_name'];
        QueueClient::push('addPoint',$queue_content);
    }

    /**
     * 添加会员经验值
     * @param unknown $member_info
     */
    public function addExppoint($member_info) {
        if (empty($member_info)) return;

        //一天内只有第一次登录赠送经验值
        if(trim(@date('Y-m-d',$member_info['member_login_time'])) == trim(date('Y-m-d'))) return;

        //加入队列
        $queue_content = array();
        $queue_content['member_id'] = $member_info['member_id'];
        $queue_content['member_name'] = $member_info['member_name'];
        QueueClient::push('addExppoint',$queue_content);
    }

    /**
     * 取得会员安全级别
     * @param unknown $member_info
     */
    public function getMemberSecurityLevel($member_info = array()) {
        $tmp_level = 0;
        if ($member_info['member_email_bind'] == '1') {
            $tmp_level += 1;
        }
        if ($member_info['member_mobile_bind'] == '1') {
            $tmp_level += 1;
        }
        if ($member_info['member_paypwd'] != '') {
            $tmp_level += 1;
        }
        if ($member_info['id_card_bind'] == '1') {
            $tmp_level += 1;
        }
        return $tmp_level;
    }

    /**
     * 获得会员等级
     * @param bool $show_progress 是否计算其当前等级进度
     * @param int $exppoints  会员经验值
     * @param array $cur_level 会员当前等级
     */
    public function getMemberGradeArr($show_progress = false,$exppoints = 0,$cur_level = ''){
        $member_grade = C('member_grade')?unserialize(C('member_grade')):array();
        //处理会员等级进度
        if ($member_grade && $show_progress){
            $is_max = false;
            if ($cur_level === ''){
                $cur_gradearr = $this->getOneMemberGrade($exppoints, false, $member_grade);
                $cur_level = $cur_gradearr['level'];
            }
            foreach ($member_grade as $k=>$v){
                if ($cur_level == $v['level']){
                    $v['is_cur'] = true;
                }
                $member_grade[$k] = $v;
            }
        }
        return $member_grade;
    }

    /**
     * 获得某一会员等级
     * @param int $exppoints
     * @param bool $show_progress 是否计算其当前等级进度
     * @param array $member_grade 会员等级
     */
    public function getOneMemberGrade($exppoints,$show_progress = false,$member_grade = array()){
        if (!$member_grade){
            $member_grade = C('member_grade')?unserialize(C('member_grade')):array();
        }
        if (empty($member_grade)){//如果会员等级设置为空
            $grade_arr['level'] = -1;
            $grade_arr['level_name'] = '暂无等级';
            return $grade_arr;
        }

        $exppoints = intval($exppoints);

        $grade_arr = array();
        if ($member_grade){
            foreach ($member_grade as $k=>$v){
                if($exppoints >= $v['exppoints']){
                    $grade_arr = $v;
                }
            }
        }
        //计算提升进度
        if ($show_progress == true){
            if (intval($grade_arr['level']) >= (count($member_grade) - 1)){//如果已达到顶级会员
                $grade_arr['downgrade'] = $grade_arr['level'] - 1;//下一级会员等级
                $grade_arr['downgrade_name'] = $member_grade[$grade_arr['downgrade']]['level_name'];
                $grade_arr['downgrade_exppoints'] = $member_grade[$grade_arr['downgrade']]['exppoints'];
                $grade_arr['upgrade'] = $grade_arr['level'];//上一级会员等级
                $grade_arr['upgrade_name'] = $member_grade[$grade_arr['upgrade']]['level_name'];
                $grade_arr['upgrade_exppoints'] = $member_grade[$grade_arr['upgrade']]['exppoints'];
                $grade_arr['less_exppoints'] = 0;
                $grade_arr['exppoints_rate'] = 100;
            } else {
                $grade_arr['downgrade'] = $grade_arr['level'];//下一级会员等级
                $grade_arr['downgrade_name'] = $member_grade[$grade_arr['downgrade']]['level_name'];
                $grade_arr['downgrade_exppoints'] = $member_grade[$grade_arr['downgrade']]['exppoints'];
                $grade_arr['upgrade'] = $member_grade[$grade_arr['level']+1]['level'];//上一级会员等级
                $grade_arr['upgrade_name'] = $member_grade[$grade_arr['upgrade']]['level_name'];
                $grade_arr['upgrade_exppoints'] = $member_grade[$grade_arr['upgrade']]['exppoints'];
                $grade_arr['less_exppoints'] = $grade_arr['upgrade_exppoints'] - $exppoints;
                $grade_arr['exppoints_rate'] = round(($exppoints - $member_grade[$grade_arr['level']]['exppoints'])/($grade_arr['upgrade_exppoints'] - $member_grade[$grade_arr['level']]['exppoints'])*100,2);
            }
        }
        return $grade_arr;
    }

    /**
     * 添加一个用于发送服务通知的formid
     * @param $condition
     * @param $formid
     * @param bool $is_prepay 是否是prepay_id
     * @return bool
     */
    public function pushFormId($condition,$formid,$is_prepay=false){
        if(empty($condition) || !is_numeric($formid)){
            return false;
        }
        $old_formid = $this->getMemberInfo($condition,array('form_ids'));
        $formid_arr = unserialize($old_formid['form_ids']);
        if(!$formid_arr){
            $formid_arr = array();
        }
        //判断是否已存在
        if(in_array($formid,array_column($formid_arr,'formid'))){
            return true;
        }
        if($is_prepay){
            array_push($formid_arr,array('formid'=>$formid,'residue'=>3,'add_time'=>TIMESTAMP));
        }else{
            array_push($formid_arr,array('formid'=>$formid,'residue'=>1,'add_time'=>TIMESTAMP));
        }

        return $this->editMember($condition,array('form_ids'=>serialize($formid_arr)));
    }

    /**
     * 取出一个用于发送服务通知的formid
     * @param $condition
     * @return bool
     */
    public function subtractFormId($condition){
        $old_formid = $this->getMemberInfo($condition,array('form_ids'));
        $old_formid = $old_formid['form_ids'];
        if($old_formid){
            $formid_arr = unserialize($old_formid);
            if(empty($formid_arr)) return '';
        }else{
            return '';
        }

        //删除过期的（7天前）
        $time = TIMESTAMP - 604800;
        $formid_arr = array_filter($formid_arr,function($v)use($time){return !($v['add_time']<=$time);});

        $form_id = array_shift($formid_arr);
        if(1<$form_id['residue']){
            $form_id['residue'] = $form_id['residue']-1;
            array_unshift($formid_arr,$form_id);
        }
        $update_formids = $this->editMember($condition,array('form_ids'=>serialize($formid_arr)));

        if($update_formids){
            return $form_id['formid'];
        }else{
            return '';
        }
    }

    /**
     * 获取所有虚拟用户
     * @return array
     * */
    public function getRobotList(){
        $robot=$this->table("member")->where("member_passwd = '虚拟用户'")->field("member_id,member_avatar,member_name")->limit(false)->select();
        return $robot[array_rand($robot,1)];
    }

    /**
     * 检查是否是新人 -- 检查是否存在订单
     * @param  integer $member_id 会员id
     * @return bool true - 是新用户 / false - 不是新用户
     */
    public function checkIfNewbie($member_id = 0)
    {
        $result = false;
        $member_id = (int)$member_id;
        if (!$member_id) {
            $this->setErrorInfo('抱歉，会员id不能为空');
            return $result;
        }
        $if_newbie = Model('order')->table('orders')->field('order_id')->where(['buyer_id' => $member_id])->find();
        if (!empty($if_newbie)) {
            $this->setErrorInfo('抱歉不是新人用户，不能领取');
            return $result;
        }
        return true;
    }

    /**
     * 获取会员微信昵称
     * @param  integer $member_id 会员id
     * @param  bool $return_type 无微信昵称返回类型， true - 返回账号昵称 / false - 返回空字符串
     * @return string
     */
    public function getMemberWxInfo($member_id = 0, $return_type = true)
    {
        $member_info = $this->getMemberInfoByID($member_id, 'member_name,weixin_info');
        if (empty($member_info)) return '';
        $weixin_info = unserialize($member_info['weixin_info']);
        return (is_array($weixin_info) && isset($weixin_info['nickname'])) ? $weixin_info['nickname'] : ($return_type ? $member_info['member_name'] : '');
    }

}
